﻿using System.Collections.Generic;
using System.ComponentModel.Composition;
using NerdWare.Crm2011VsTools.Core.Crm;
using microsoft.crm.sdk.DiscoveryService;

namespace NerdWare.CrmPlugin.Crm4OnPremise64
{
    [Export(typeof(IDiscoverCrm))]
    [ExportMetadata("CrmVersion", CrmVersionEnum.Crm40)]
    public class Discovery : DiscoverCrmBase
    {
        public override void Discover()
        {
            using (CrmDiscoveryService discoveryService = new CrmDiscoveryService())
            {
                discoveryService.Url = base.CrmApplicationDescriptor.GetDiscoveryUrl();
                discoveryService.Credentials = base.CrmApplicationDescriptor.GetCredentials();

                RetrieveOrganizationsRequest organisationsRequest = new RetrieveOrganizationsRequest();
                RetrieveOrganizationsResponse organizationsResponse = (RetrieveOrganizationsResponse)discoveryService.Execute(organisationsRequest);

                createOrganizationDictionary(organizationsResponse);
            }
        }

        private void createOrganizationDictionary(RetrieveOrganizationsResponse organizationsResponse)
        {
            base.Organizations = new List<OrgDetail>();
            foreach (OrganizationDetail organizationDetail in organizationsResponse.OrganizationDetails)
            {
                OrgDetail orgDetail = new OrgDetail
                {
                    OrganizationName = organizationDetail.OrganizationName,
                    OrganizationId = organizationDetail.OrganizationId,
                    OrganizationVersion = organizationDetail.OrganizationVersion,
                    OrganizationFriendlyName = organizationDetail.FriendlyName,
                    CrmService = organizationDetail.CrmServiceUrl,
                    MetaService = organizationDetail.CrmMetadataServiceUrl,
                    CrmVersion = CrmVersionEnum.Crm40,
                    WebAppUrl = organizationDetail.WebApplicationUrl
                };

                base.Organizations.Add(orgDetail);
            }
        }
    }
}
